const db = require('../db/index')
const jwt = require('jsonwebtoken')
const config = require('../config.js')


exports.regUser = (req, res) =>{
    res.send('reguser OK')
}


exports.login = (req, res) =>{
    const sql = 'select * from sys_user where user=? and password=?';
    const user = req.body.user;
    const password = req.body.password
    const arr = [user, password];
    db.query(sql, arr, (err,result) => {
        const user = {...result[0], password:''}
        const tokenStr = jwt.sign(user, config.jwtSecretKey, { expiresIn:'1h'})
        if(result.length > 0){
            res.send({
                status:200,
                result,
                token:tokenStr
            })
        }else{
            res.send({
                status:401,
                msg:'登录失败'
            })
        }
    })
}

exports.getIndex = (req, res) =>{
    db.query(sqlStr, (err, results ) => {
        if(err) throw err
        res.send(results)
    })
}
exports.updateIndex = (req, res) => {
    console.log(req.body)
    const id =req.body.id
    // const title = req.body.title
    const image =req.body.image
    const sql = 'update sys_lunbotu set image=? where id=?'
    const arr = [ image,id]
    db.query(sql,arr,(err, results) => {
       if(err) throw err
       res.send({
           data:req.body,
           msg:'修改成功'})
        
    })
}
exports.getLunbotu = (req, res) =>{
    db.query('select * from sys_lunbotu', (err, results ) => {
        if(err) throw err
        res.send(results)
    })
}

exports.updateLunbotu = (req, res) => {
    const sql = 'update sys_lunbotu set image=? where id=?'
    const image = req.body.image
    const id = req.body.id
    db.query(sql, [image, id],(err, res) =>{
        if(err) throw err
        res.send({
            data:req.body,
            msg:'修改成功'
        })
    })
}

exports.addLunbotu = (req, res) => {
    const sql = `INSERT INTO sys_ceshi (image) VALUES('${req.body.image}');`
    console.log(sql)
    
    db.query(sql,(err, results) =>{
        console.log(results);
    
        if(err) {
            res.send("新增失败"+err)
        }else{
             res.send('新增成功')
        }
       
    })
}

// 定义sql语句
const sqlStr = 'select * from sys_index'